use crate::model::user::User;
use sqlx::{Error, MySqlPool, Row};

pub struct UserDao<'a> {
    db: &'a MySqlPool,
}

impl UserDao<'_> {
    pub fn new(db: &MySqlPool) -> UserDao {
        UserDao { db }
    }

    pub async fn select_by_account(&self, account: &String) -> Result<User, Error> {
        let result = sqlx::query("select * from user where account = ?")
            .bind(account)
            .map(|row| User {
                id: row.get("id"),
                username: row.get("username"),
                account: row.get("account"),
                password: row.get("password"),
                captcha: None,
            })
            .fetch_one(self.db)
            .await;
        result
    }

    pub async fn account_is_exist(&self, account: &String) -> bool {
        let result = sqlx::query("select account from user where account = ?")
            .bind(account)
            .fetch_one(self.db)
            .await;
        result.is_ok()
    }

    pub async fn add(&self, user: User) -> bool {
        let result = sqlx::query("insert into user(account, password, username) values(?,?,?)")
            .bind(user.account)
            .bind(user.password)
            .bind(user.username)
            .execute(self.db)
            .await
            .expect("添加用户失败！");
        result.rows_affected() != 0
    }
}
